using System;
using System.Web.Security;
using Castle.MonoRail.Framework;
using Castle.MonoRail.ActiveRecordSupport;
using DecisionesInteligentes.iEvalua.Models;
using DecisionesInteligentes.iEvalua.Web.Services;

namespace DecisionesInteligentes.iEvalua.Web.Controllers
{
	[Layout("default")]
	public class LoginController : BaseController<User>
	{
		private readonly ISecurityService securityService;
		private readonly IAuthenticationService authenticationService;
		
		public LoginController(ISecurityService securityService, IAuthenticationService authenticationService)
		{
			this.securityService = securityService;
			this.authenticationService = authenticationService;
		}
		
		public override void Index()
		{
			
		}
		
		public void AuthenticateUser(string username, string password, bool rememberMe, string currentAction)
		{
			User user = securityService.Authenticate(username, password, Application.Id);
			
			if(user == null)
			{
				Flash["login_message"] = "User name does not exists";
				RedirectToAction("Index");
				return;
			}
			
			if (!securityService.VerifyPassword(password, user.Password))
			{
				Flash["login_username"] = username;
				Flash["login_message"] = "Invalid Password";
				RedirectToAction("Index");
				return;
			}
			
			authenticationService.SetAuthCookie(Context, user, rememberMe, GetCookiePath());
			//AddAuthenticationTicket(user);
			
			Redirect(currentAction);
		}
		
		private string GetCookiePath()
		{
			if (Context == null)
			{
				return "ievalua";
			}

			return Context.ApplicationPath + "/";
		}
	}
}
